<template>
  <div class="container">
    <el-form ref="form" label-width="120px" label-position="left" style="padding: 0 10px">
      <div class="c-box">
        <!-- 基础信息部分 -->
        <div class="upload-title-box">
          <div class="upload-title">基本信息</div>
        </div>
        <hk-form
          ref="hkFormRef1"
          :form-labels="basicArr"
          :rules="formRules"
          :data="formData"
          :dict-list="dictList"
          :btn-hidden="true"
          label-width="120" />
      </div>
      <div class="c-box">
        <div class="upload-title-box">
          <div class="upload-title">盘点范围及对象</div>
        </div>
        <hk-form
          ref="hkFormRef2"
          :data="queryParams"
          :form-labels="fieldList"
          :dict-list="dictList"
          :btn-hidden="true"
          label-width="120"
          @handleEvent="handleEvent">
          <template #filter-assetTypes>
            <div class="ca-select clearfix">
              <el-select
                ref="selectIt"
                v-model="queryParams.assetValue"
                :options="citiesList"
                style="width: 100%"
                class="fake"
                multiple
                @change="clearSelect"
                @focus="selectFocus">
                <el-option v-for="item in citiesList" :key="item.id" :label="item.dictValue" :value="item.id" />
              </el-select>
              <el-cascader
                ref="cascader"
                v-model="queryParams.assetTypes"
                filterable
                :options="dictList.typeList"
                :props="assetProps"
                :show-all-levels="false"
                clearable
                style="width: 100%"
                class="test"
                :collapse-tags="false"
                @expand-change="expandChange"
                @change="handleChange($event, 'cascader')" />
            </div>
          </template>
          <template #filter-departmentIds>
            <treeselect
              v-model="queryParams.departmentIds"
              :options="dictList.deptList"
              :normalizer="normalizer"
              :append-to-body="true"
              :multiple="true"
              placeholder="请选择责任部门"
              @input="changeOrg" />
          </template>
          <template #filter-list>
            <hk-table
              :table-data="tableData"
              :table-columns="tableList"
              :selection="false"
              :show-index="true"
              :total="total"
              :loading="loading"
              :table-height="680"
              :common-fixed="true"
              :query-params="queryParams"
              :pager-count="5"
              @changePage="getListData">
              <template #assetName="scope">
                <el-button size="mini" type="text" @click="toDetail(scope.row)">{{ scope.row.assetName }}</el-button>
              </template>
              <template #assetCode="scope">
                <el-button size="mini" type="text" @click="toDetail(scope.row)">{{ scope.row.assetCode }}</el-button>
              </template></hk-table
            >
          </template>
        </hk-form>
      </div>
    </el-form>
    <div class="my-foot">
      <el-button @click="submitForm(true)">保存并导出任务</el-button>
      <el-button type="primary" @click="submitForm(false)">仅保存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import HkForm from '@/components/Hk-Form'
import HkTable from '@/components/Hk-Table/index.vue'

import { dictItemsList, assetDict } from '@/api/specialProject/asset'
import { queryAssetByTask, add, update, getDetail } from '@/api/specialProject/Inventory'
import { treeSelect } from '@/api/specialProject/personnel'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'
export default {
  components: { HkForm, HkTable, Treeselect },
  beforeRouteLeave(to, from, next) {
    console.log(to, '路由')
    if (to.path === '/specialProject/assets/assetLibraryDetail') {
      const condition = JSON.stringify(this.queryParams)
      const fd = JSON.stringify(this.formData)
      const citiesList = JSON.stringify(this.citiesList)
      sessionStorage.setItem('condition', condition)
      sessionStorage.setItem('fd', fd)
      sessionStorage.setItem('citiesList', citiesList)
    } else {
      sessionStorage.removeItem('condition')
      sessionStorage.removeItem('fd')
      sessionStorage.removeItem('citiesList')
    }
    next()
  },
  beforeRouteEnter(to, from, next) {
    console.log(to, '路由')
    if (from.path !== '/specialProject/assets/assetLibraryDetail') {
      sessionStorage.removeItem('condition')
      sessionStorage.removeItem('fd')
      sessionStorage.removeItem('citiesList')
    }
    next()
  },
  data() {
    return {
      // 表单数据
      // 分页总条数
      total: 0,
      // 仅展示必填信息
      showMore: false,
      showRequired: false,
      formData: {
        taskName: '',
        taskNotes: '',
        departmentIds: null,
        assetTypes: null,
        positionIds: null,
      },
      assetProps: {
        children: 'children',
        label: 'dictValue',
        value: 'id',
        emitPath: false,
        multiple: true,
      },
      // 表格
      tableList: [
        { label: '设备名称', param: 'assetName', type: 'slot' },
        { label: '设备编号', param: 'assetCode', type: 'slot' },
        { label: '设备IP', param: 'ip' },
        { label: '设备类别/类型', param: 'assetType' },
        { label: '设备状态', param: 'status' },
        { label: '责任人', param: 'ownerName' },
        { label: '存放区域', param: 'storageDistrictName' },
        { label: '存放位置', param: 'storageLocation' },
      ],
      tableData: [],
      queryParams: {
        current: 1,
        size: 10,
        assetValue: [],
        departmentIds: [],
      },
      // 表1 基础信息
      basicArr: [
        {
          label: '任务名称',
          field: 'taskName',
          type: 'input',
          maxlength: 20,
          span: 13,
        },
        {
          label: '任务描述',
          field: 'taskNotes',
          type: 'textarea',
          maxlength: 500,
          span: 13,
        },
        {
          label: 'id',
          field: 'id',
          type: 'input',
          hidden: true,
        },
      ],
      // 搜索框
      fieldList: [
        {
          label: '责任部门',
          field: 'departmentIds',
          type: 'slot',
          span: 13,
        },
        {
          label: '设备类型',
          type: 'slot',
          // type: 'cascader',
          field: 'assetTypes',
          list: 'typeList',
          span: 13,
        },

        {
          label: '存放区域',
          field: 'positionIds',
          type: 'select',
          list: 'regionList',
          multiple: true,
          span: 13,
        },
        {
          label: '盘点对象',
          field: 'list',
          type: 'slot',
          span: 24,
        },
      ],

      // 表单校验
      formRules: {
        taskName: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      dictList: {
        regionList: [],
        typeList: [],
        deptList: [],
      },
      loading: false,

      nodeList: [],
      citiesList: [],
      resArr: [],
      knowId: null,
    }
  },
  computed: {},
  async created() {
    var cd = sessionStorage.getItem('condition')
    if (cd) {
      var condition = JSON.parse(cd)
      this.queryParams = condition
    }
    var citiesList = sessionStorage.getItem('citiesList')
    if (citiesList) {
      var ct = JSON.parse(citiesList)
      this.citiesList = ct
    }
    var fd = sessionStorage.getItem('fd')
    if (fd) {
      var data = JSON.parse(fd)
      this.formData = data
    }

    this.knowId = this.$route.query?.id
    if (this.$route.query.id) {
      await this.getDetailData()
      this.getConfigureObj()
    } else {
      this.getConfigureObj()
      this.getListData()
    }
  },
  mounted() {},
  methods: {
    getDetailData() {
      getDetail(this.knowId).then((res) => {
        this.formData = res
        this.queryParams.departmentIds = res.departmentIds || []
        this.queryParams.assetTypes = res.assetTypes
        this.citiesList = res.dictItemsList
        this.queryParams.positionIds = res.positionIds
        var ar = res.dictItemsList.map((item) => {
          return item.id
        })
        this.queryParams.assetValue = ar

        this.getListData()
      })
    },
    toDetail(row) {
      console.log(row)
      this.$router.push({
        path: '/specialProject/assets/assetLibraryDetail',
        query: {
          id: row.id,
          title: '详情',
          dictValue: row.dictItems.dictValue,
          dictKey: row.dictItems.dictKey,
          dictId: row.dictItems.id,
        },
      })
    },
    handleEvent(e) {
      console.log(e)
      if (e.field === 'positionIds') {
        this.queryParams.positionIds = e.value
        this.handleQuery()
      }
    },
    // 部门change事件
    changeOrg(node) {
      console.log(node, 'ss')
      this.queryParams.departmentIds = node
      this.handleQuery()
    },
    // 搜索按钮
    handleQuery(val) {
      this.queryParams.current = 1
      this.getListData()
    },
    getListData() {
      this.loading = true
      var obj = { ...this.queryParams }
      obj.assetTypes = obj.assetValue
      delete obj.assetValue
      console.log(obj, 'oooooooo')
      queryAssetByTask(obj).then((res) => {
        // 返回值为null，展示---
        res.list.forEach((element) => {
          for (const key in element) {
            element[key] = element[key] || '—'
          }
        })
        this.tableData = res.list
        this.total = res.total
        this.loading = false
        const condition = JSON.stringify(this.queryParams)
        const fd = JSON.stringify(this.formData)
        const citiesList = JSON.stringify(this.citiesList)
        sessionStorage.setItem('condition', condition)
        sessionStorage.setItem('fd', fd)
        sessionStorage.setItem('citiesList', citiesList)
      })
    },
    async clearSelect(e) {
      const result = this.nodeList.filter((item) => e.includes(item.value))
      if (!result) {
        this.queryParams.assetValue = []
        this.citiesList = []
        this.queryParams.assetTypes = []
        this.handleQuery()
      } else {
        this.nodeList = result
        const idArr = []
        this.citiesList = []
        for (let i = 0; i < result.length; i++) {
          idArr.push(result[i].value)
          this.citiesList.push(result[i].data)
        }
        this.queryParams.assetValue = idArr
        this.resArr = []
        console.log(result)
        await this.getNodeId(result)
        console.log(this.queryParams.assetValue, ' this.queryParams.assetValue')
        this.queryParams.assetTypes = this.resArr
        this.handleQuery()
      }
    },
    // 抽取树节点以及所有子节点的id 构成数组
    getNodeId(array) {
      for (var item of array) {
        this.resArr.push(item.value)
        if (item.children.length > 0) {
          this.getNodeId(item.children)
        }
      }
    },
    selectFocus() {
      var that = this
      this.$refs.selectIt.blur()
      var timer = setInterval(() => {
        that.$refs.cascader.toggleDropDownVisible(true)
        clearInterval(timer)
      }, 200)
    },
    // 级联框
    handleChange(e, item) {
      if (!e) {
        this.queryParams.assetValue = []
        this.citiesList = []
      } else {
        let nodeList = this.$refs[item].getCheckedNodes()
        // 如果三级全选就显示二级的，没有全选就显示三级的
        nodeList = nodeList.filter((option) => !(option.parent && option.parent.checked))
        this.nodeList = nodeList
        const idArr = []
        this.citiesList = []
        for (let i = 0; i < nodeList.length; i++) {
          idArr.push(nodeList[i].value)
          this.citiesList.push(nodeList[i].data)
        }
        this.queryParams.assetValue = idArr
      }
      console.log(e, this.queryParams.assetValue, 'idArr')
      this.queryParams.assetTypes = e
      this.handleQuery()
    },
    // 解决级联选死机问题
    expandChange() {
      this.$nextTick(() => {
        // 添加这段代码
        const $el = document.querySelectorAll('.el-cascader-panel .el-cascader-node[aria-owns]')
        Array.from($el).map((item) => item.removeAttribute('aria-owns'))
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      }
    },
    /** 获取执行配置下拉框的数据 */
    getConfigureObj() {
      //   获取周期性执行 分钟/小时
      // getDictList('cronCycle').then((res) => {
      //   this.cycleNodeOption = res
      // })
      dictItemsList({ parentId: 0 }).then((res) => {
        this.dictList.typeList = res
      })
      treeSelect().then((res) => {
        this.dictList.deptList = res
      })
      assetDict('deposit_region').then((res) => {
        this.dictList.regionList = res.map((o) => {
          o.label = o.name
          o.value = o.id
          return o
        })
      })
    },

    // 提交事件
    submitForm(isDown) {
      console.log(isDown, 'eeeee')
      this.$refs.hkFormRef1.handleFormSubmit('formLabels').then((res) => {
        if (this.tableData.length === 0) {
          this.$message.error('盘点对象为空，请重新选择盘点范围')
          return false
        }
        var data = {
          ...res,
        }
        var send = {
          ...res,
        }
        // data.assetTypes = this.queryParams.assetTypes.toString()
        console.log(this.queryParams, 'this.queryParams')
        data.assetTypes = this.queryParams.assetValue !== null ? this.queryParams.assetValue.toString() : null
        data.departmentIds = this.queryParams.departmentIds !== null ? this.queryParams.departmentIds.toString() : null
        data.positionIds = this.queryParams.positionIds !== null ? this.queryParams.positionIds.toString() : null

        send.assetTypes = this.queryParams.assetValue !== null ? this.queryParams.assetValue : null
        send.departmentIds = this.queryParams.departmentIds !== null ? this.queryParams.departmentIds : null
        send.positionIds = this.queryParams.positionIds !== null ? this.queryParams.positionIds : null
        console.log(send, 'sdedd')
        if (!this.$route.query.id) {
          add(data).then((ress) => {
            this.$message.success('新增成功')
            if (isDown) {
              var obj = {
                departmentIds: send.departmentIds || null,
                assetTypes: send.assetTypes || null,
                positionIds: send.positionIds || null,
                id: ress,
                taskName: send.taskName,
              }
              this.handleExport(obj)
            }
            setTimeout(() => {
              this.cancel()
            }, 100)
          })
        } else {
          update(data).then((res) => {
            this.$message.success('修改成功')
            if (isDown) {
              var obj = {
                departmentIds: send.departmentIds || null,
                assetTypes: send.assetTypes || null,
                positionIds: send.positionIds || null,
                id: send.id,
                taskName: send.taskName,
              }
              this.handleExport(obj)
            }
            setTimeout(() => {
              this.cancel()
            }, 100)
          })
        }
      })
    },
    // 导出
    handleExport(e) {
      var obj = {
        departmentIds: [],
        assetTypes: [],
        positionIds: [],
        taskId: e.id,
      }
      if (e.departmentIds === '—') {
        obj.departmentIds = []
      } else {
        obj.departmentIds = e.departmentIds
      }
      if (e.assetTypes === '-') {
        obj.assetTypes = []
      } else {
        obj.assetTypes = e.assetTypes
      }
      if (e.positionIds === '-') {
        obj.positionIds = []
      } else {
        obj.positionIds = e.positionIds
      }
      this.smDownload(
        window.baseUrl.action + '/assetInventory/export',
        obj,
        `${e.taskName}${new Date().getTime()}.xlsx`
      )
    },
    // 关闭按钮
    cancel() {
      this.$router.go(-1)
    },
  },
}
</script>

  <style lang="scss" scoped>
.flexBox {
  display: flex;
  justify-content: flex-start;
}
.ca-select {
  width: 100%;
  min-height: 32px;
  .fake {
    float: left;
    z-index: 9;
  }
  .test {
    float: left;
    visibility: hidden;
    width: 0px;
    height: 0px;
    z-index: -1;
  }
}
#app.dark-theme {
  .container,
  .my-foot {
    background: transparent !important;
  }
  .c-box {
    background: rgba(59, 139, 255, 0.1);
  }
  .sp-flex i {
    color: #4b6eef !important;
  }
}

.tag {
  height: 32px;
  line-height: 32px;
  width: 80px;
  text-align: center;
}
.upload-title-box {
  height: 40px;
  width: 100%;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  // border-bottom: 1px solid rgba($color: #000000, $alpha: 8%);

  .upload-title {
    font-size: 16px;
    font-weight: 700;
    color: #000000;
  }
}
.container {
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #eef0f5;
}
.c-box {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.el-form {
  flex: 1;
  overflow: auto;
}
.my-foot {
  height: 70px;
  background: #fff;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 20px;
}
::v-deep .el-table__body-wrapper {
  height: 470px;
}
::v-deep {
  .el-form-item__content {
    line-height: 20px !important;
  }
  .el-upload-list {
    display: none;
  }
  .el-table {
    height: auto;
  }
  .el-input-group__append {
    background: transparent;
  }
  .content {
    width: 100%;
    justify-content: flex-end;
    // margin: -20px 0;
  }
  .configuration-situation {
    border-top: 1px solid #e8e8e8;
    margin-bottom: 0;
    .left {
      border-right: 1px solid #e8e8e8;
    }
  }
}
</style>

